package com.mmlc.meimei.lichengkongjian.classify;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.requestbean.BaseResponseBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.google.gson.Gson;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.network.filter.AllPcaListRequestFilter;
import com.mmlc.network.filter.EditAddressRequestFilter;
import com.mmlc.network.responsebean.AddressListResponseBean;
import com.mmlc.network.responsebean.AllPcaListResponseBean;
import com.mmlc.utils.EditInputUtils;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.ViewUtils;
import com.mmlc.widget.AddressSelectorView;

import org.apache.http.util.EncodingUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EditInformationActivity extends InterActivity {


    @Override
    protected int initContentView() {
        return R.layout.activity_edit_information;
    }

    String id;
    int type, position;
    int currentProvinceIndex = -1, currentCityIndex = -1, currentDistrictIndex = -1;
    AddressListResponseBean.DataBean address;

    @Override
    protected void initExtra() {
        super.initExtra();
        id = getIntent().getStringExtra("id");
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            position = getIntent().getIntExtra("position", -1);
            address = (AddressListResponseBean.DataBean) getIntent().getSerializableExtra("address");
        } else {
            address = new AddressListResponseBean.DataBean();
        }
    }

    EditText edt_name, edt_phone, edt_street,edt_idcard;
    TextView tv_title, tv_address,tv_name,tv_number,tv_city,tv_street,tv_idcard;

    @Override
    protected void initView() {
        tv_title = ViewUtils.getView(activity, R.id.tv_title);
        tv_name = ViewUtils.getView(activity, R.id.tv_name);
        tv_number = ViewUtils.getView(activity, R.id.tv_number);
        tv_city = ViewUtils.getView(activity, R.id.tv_city);
        tv_street = ViewUtils.getView(activity, R.id.tv_street);
        tv_idcard = ViewUtils.getView(activity, R.id.tv_idcard);
        edt_name = ViewUtils.getView(activity, R.id.edt_name);
        edt_phone = ViewUtils.getView(activity, R.id.edt_phone);
        tv_address = ViewUtils.getView(activity, R.id.tv_address);
        edt_street = ViewUtils.getView(activity, R.id.edt_street);
        edt_idcard = ViewUtils.getView(activity, R.id.edt_idcard);

        setEditStyle(edt_name,"姓名");
        setEditStyle(edt_phone,"电话号码");
        setEditStyle(edt_street,"街道/门牌号");
        setEditStyle(edt_idcard,"身份证号码(跨境直购必填)");

        if (type == 0) {
            tv_title.setText("增加地址");
        } else if (type == 1) {
            tv_title.setText("修改地址");
            showUI();
            if (address != null) {
                edt_name.setText(address.getContactor());
                edt_phone.setText(address.getPhone());
                tv_address.setText(address.getProvince_name() + "/" + address.getCity_name() + "/" + address.getArea_name());
                if(!TextUtils.isEmpty(address.getId_card())){
                    edt_idcard.setText(address.getId_card() + "");
                }
                if (!ViewUtils.isEmpty(address.getAddress())) {
                    edt_street.setText(address.getAddress());
                }
            }
        }
    }


    public void showUI(){
        tv_name.setVisibility(View.VISIBLE);
        tv_number.setVisibility(View.VISIBLE);
        tv_city.setVisibility(View.VISIBLE);
        tv_street.setVisibility(View.VISIBLE);
        tv_idcard.setVisibility(View.VISIBLE);
    }
    @Override
    protected void initInfo() {
        super.initInfo();

//        String allPcaList = (String) SPUtils.get(context, "allPcaList", "");
//        if (!ViewUtils.isEmpty(allPcaList)) {
//            AllPcaListResponseBean responseBean = new Gson().fromJson(allPcaList, AllPcaListResponseBean.class);
//            getList(responseBean);
//        } else {
        getAllPcaList();
//        }
    }

    private String getAsset() {
        String result = "";
        try {
            AssetManager assetManager = getAssets();
            InputStream is = assetManager.open("cities.txt");
            int length = is.available();
            byte[] buffer = new byte[length];
            is.read(buffer);

            result = EncodingUtils.getString(buffer, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 待初始化
     */
    List<String> mProvinceDatas = new ArrayList<>();
    Map<String, List<String>> mCitiesDatasMap = new HashMap<>();
    Map<String, List<String>> mDistrictDatasMap = new HashMap<>();
    Map<String, String> nameToIds = new HashMap<>();
    Map<String, String> idToNames = new HashMap<>();

    /**
     * 获取城市列表
     */
    private void getAllPcaList() {
        AllPcaListRequestFilter filter = new AllPcaListRequestFilter((BaseParentActivity) activity);
        filter.requestBean.method = "allPcaList";
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<AllPcaListResponseBean>() {
            @Override
            public void onSuccess(AllPcaListResponseBean result) {
                if (result == null) {
                    result = new Gson().fromJson(getAsset(), AllPcaListResponseBean.class);
//                } else {
//                    SPUtils.put(context, "allPcaList", new Gson().toJson(result));
                }
                if (result.getCode() == 0 || result.getData() == null) {
                    result = new Gson().fromJson(getAsset(), AllPcaListResponseBean.class);
                }
                getList(result);
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {

            }
        });
    }

    List<AllPcaListResponseBean.DataBean> data;

    /**
     * 解析城市列表
     */
    public void getList(AllPcaListResponseBean result) {
        if (result != null) {
            if (result.getCode() == 0) {
                data = result.getData();
                for (AllPcaListResponseBean.DataBean bean : data) {
                    nameToIds.put(bean.getName(), bean.getCid());
                    idToNames.put(bean.getCid(), bean.getName());
                    if (bean.getParentId() != null && "province".equals(bean.getType())) {
                        if (type == 1 && bean.getCid().equals(address.getProvince_id())) {
                            currentProvinceIndex = mProvinceDatas.size();
                        }
                        mProvinceDatas.add(bean.getName());
                        mCitiesDatasMap.put(bean.getName(), new ArrayList<String>());
                    } else if (bean.getParentId() != null && "city".equals(bean.getType())) {
                        List<String> cities = mCitiesDatasMap.get(idToNames.get(bean.getParentId()));
                        if (cities == null) {
                            cities = new ArrayList<>();
                        }

                        if (type == 1 && bean.getParentId().equals(address.getProvince_id()) && bean.getCid().equals(address.getCity_id())) {
                            currentCityIndex = cities.size();
                        }

                        cities.add(bean.getName());
                        mCitiesDatasMap.put(idToNames.get(bean.getParentId()), cities);
                        mDistrictDatasMap.put(bean.getName(), new ArrayList<String>());
                    } else if (bean.getParentId() != null && "area".equals(bean.getType())) {
                        List<String> districts = mDistrictDatasMap.get(idToNames.get(bean.getParentId()));
                        if (districts == null) {
                            districts = new ArrayList<>();
                        }

                        if (type == 1 && bean.getParentId().equals(address.getCity_id()) && bean.getCid().equals(address.getArea_id())) {
                            currentDistrictIndex = districts.size();
                        }

                        districts.add(bean.getName());
                        mDistrictDatasMap.put(idToNames.get(bean.getParentId()), districts);
                    }
                }
            }
        }
    }

    @Override
    protected void initEvent() {
        ViewUtils.getView(activity, R.id.iv_back).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.tv_verify).setOnClickListener(this);

        tv_address.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_address:
                initSelectorDialog();
                break;
            case R.id.tv_verify:
                verify();
                break;
        }
    }

    private void verify() {
        if (ViewUtils.isEmpty(edt_name.getText().toString())) {
            ToastUtils.showToast("请输入 姓名");
        } else if (ViewUtils.isEmpty(edt_phone.getText().toString())) {
            ToastUtils.showToast("请输入 电话号码");
        } else if (!ViewUtils.isEmpty(edt_phone.getText().toString()) && !EditInputUtils.checkedPhoneNumber(edt_phone.getText().toString())) {
            ToastUtils.showToast("请输入正确的 电话号码");
        } else if (ViewUtils.isEmpty(tv_address.getText().toString())) {
            ToastUtils.showToast("请选择 省/市/区");
        } else if (ViewUtils.isEmpty(edt_street.getText().toString())) {
            ToastUtils.showToast("请输入 街道/门牌号");
        } else {
            address.setContactor(edt_name.getText().toString());
            address.setPhone(edt_phone.getText().toString());
            address.setAddress(edt_street.getText().toString());
            address.setId_card(edt_idcard.getText().toString());
            EditAddressRequestFilter filter = new EditAddressRequestFilter(activity);
            if (type == 1) {
                filter.requestBean.method = "editAddress";
                filter.requestBean.aid = address.getId();
            }
            filter.requestBean.contactor = address.getContactor();
            filter.requestBean.phone = address.getPhone();
            filter.requestBean.address = address.getAddress();
            filter.requestBean.province_id = Integer.parseInt(address.getProvince_id());
            filter.requestBean.city_id = Integer.parseInt(address.getCity_id());
            filter.requestBean.area_id = Integer.parseInt(address.getArea_id());
            filter.requestBean.id_card =address.getId_card();
            filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
                @Override
                public void onSuccess(BaseResponseBean result) {
                    if (result != null && result.getCode() == 0) {
                        editSuccess();
                    } else {
                        editFailure();
                    }
                }

                @Override
                public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                    if (serverError != null) {
                        ToastUtils.showToast(serverError.mess.toString());
                    }
                }
            });

        }
    }

    private void editSuccess() {
        Intent intent = new Intent();
        intent.putExtra("type", type).putExtra("address", address);
        if (type == 1) {
            intent.putExtra("position", position);
        }
        setResult(200, intent);
        finish();
    }

    private void editFailure() {
        ToastUtils.showToast("网络不稳定，地址" + (type == 1 ? "修改失败" : "增加失败"));
    }

    Dialog dialog;
    View view;
    AddressSelectorView selector;

    private void initSelectorDialog() {
        if (dialog == null) {
            view = getLayoutInflater().inflate(R.layout.dialog_address_selector, null);
            view.setMinimumWidth(getResources().getDisplayMetrics().widthPixels);
            dialog = new Dialog(activity, R.style.BuyDialogStyle);
            dialog.setContentView(this.view);
            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams params = dialogWindow.getAttributes();
            params.x = 0;
            params.y = 0;
            params.width = getResources().getDisplayMetrics().widthPixels;
            dialogWindow.setAttributes(params);

            selector = ViewUtils.getView(this.view, R.id.selector);
            selector.setData(mProvinceDatas, mCitiesDatasMap, mDistrictDatasMap);
            selector.setSelectedListener(new AddressSelectorView.OnSelectedListener() {
                @Override
                public void onSelected(String proviceName, int provinceIndex, String cityName, int cityIndex, String districtName, int districtIndex) {
                    dialog.hide();

                    if (address == null) {
                        address = new AddressListResponseBean.DataBean();
                    }
                    address.setProvince_name(proviceName);
                    address.setCity_name(cityName);
                    address.setArea_name(districtName);
                    address.setProvince_id(nameToIds.get(proviceName));
                    address.setCity_id(nameToIds.get(cityName));
                    address.setArea_id(nameToIds.get(districtName));

                    tv_address.setText(proviceName + "/" + cityName + "/" + districtName);
                }
            });
            if (type == 1 && address != null) {
                selector.setSelectedIndex(currentProvinceIndex, currentCityIndex, currentDistrictIndex);
            }


        }
        dialog.show();
    }


    public void setEditStyle(EditText et,String hint) {
        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString(hint);
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(14, true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        et.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }

}
